package com.rc.saas.tenant.controller.member;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.model.member.RcMemberGainGradeSetting;
import com.rc.saas.tenant.model.member.RcMemberGainGradeSettingExample;
import com.rc.saas.tenant.model.member.RcMemberGainSetting;
import com.rc.saas.tenant.model.member.RcMemberLevelSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.elec.ElecLabelSearch;
import com.rc.saas.tenant.search.ticket.TicketSearch;
import com.rc.saas.tenant.service.member.MemeberLevelService;
import com.rc.saas.tenant.service.member.RcMemberGainGradeSettingService;
import com.rc.saas.tenant.service.member.RcMemberGainSettingService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.ticket.TicketVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import com.rc.saas.tenant.vo.device.RcLabelVo;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/member/gain")
public class MemberGainController {
    private static Logger logger = LogManager.getLogger(MemberGainController.class);

    private String prefix = "/templates/member/member";

    @RequestMapping("/index")
    public String index() {
        return prefix + "/memberGain";
    }


    @RequestMapping("/indexWithSublevel/{sublevel}")
    public String indexWithSublevel(Model model, @PathVariable("sublevel") String sublevel) {
        model.addAttribute("sublevel", sublevel);
        return prefix + "/memberGain";
    }

    @Autowired
    private RcMemberGainSettingService memberGainSettingService;

    @Autowired
    private RcMemberGainGradeSettingService memberGainGradeSettingService;

    @Autowired
    private MemeberLevelService memeberLevelService;

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private UploadComponent uploadComponent;

    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;

    @ResponseBody
    @RequestMapping("/listPageMemberGain")
    public WebPageInfo listPageMemberGain(String gainName, String sublevel,
                                          @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                          @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) {
        PageInfo<RcMemberGainSetting> pageInfo = memberGainSettingService.listPageMemberGain(gainName, sublevel,  pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

	 /**
     * 导出会员权益列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(String gainName, String sublevel,
                            @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcMemberGainSetting> pageInfo = memberGainSettingService.listPageMemberGain(gainName, sublevel,  pageNo, pageSize);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("会员权益列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcMemberGainSetting.class).sheet("会员权益列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出会员权益列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }
/*
    @ResponseBody
    @RequestMapping("/updateMemberGainStatus")
    public TResponse updateMemberGainStatus(Long id, String status) {
        RcMemberGainSetting memberGainSetting = memberGainSettingService.selectByPrimaryKey(id);
        memberGainSetting.setStatus(status);
        memberGainSettingService.updateByPrimaryKeySelective(memberGainSetting);
        return TResponse.SUCCESS();
    }*/

    @RequestMapping("/addMemberGain")
    public String addMemberGain(Model model) {
        model.addAttribute("levels",memeberLevelService.loadLevels());
        model.addAttribute("parLevels",memeberLevelService.getParLevels());
        TicketSearch search = new TicketSearch();
        search.setStatus("0");
        List<TicketVo> ticketVo = tenantTicketTypeService.getTenantTickets(search);
        model.addAttribute("ticketInfos", ticketVo);
        return "/templates/member/member/addMemberGain";
    }

    @RequestMapping("/editMemberGain/{memberGainId}")
    public String editMemberGain(Model model, @PathVariable("memberGainId") Long memberGainId) {
        RcMemberGainSetting memberGainSetting = memberGainSettingService.selectByPrimaryKey(memberGainId);
        TicketSearch search = new TicketSearch();
        search.setStatus("0");
        List<TicketVo> ticketVo = tenantTicketTypeService.getTenantTickets(search);
        model.addAttribute("ticketInfos", ticketVo);
        model.addAttribute("levels",memeberLevelService.loadLevels());
        model.addAttribute("parLevels",memeberLevelService.getParLevels());
        model.addAttribute("settingInfo", memberGainSetting);
        return "/templates/member/member/editMemberGain";
    }

   /* @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        RcMemberGainSetting memberGainSetting = memberGainSettingService.selectByPrimaryKey(id);
        List<RcMemberGainGradeSetting> gainGrades = memberGainGradeSettingService.listMemberGainGradeByGainSetting(id);
        model.addAttribute("memberGainSetting", memberGainSetting);
        model.addAttribute("gainGrades", gainGrades);
        return "/templates/system/content";
    }*/

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping(value = "/deleteMemberGain", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteMemberGain(Long memberGainId) {
        RcMemberGainSetting info = memberGainSettingService.selectByPrimaryKey(memberGainId);
        if (info==null){
            return TResponse.FAIL("请求错误");
        }
       /* RcMemberGainGradeSettingExample childExample = new RcMemberGainGradeSettingExample();
        childExample.createCriteria().andMemberGainIdEqualTo(memberGainId);
        memberGainGradeSettingService.deleteByExample(childExample);*/
        memberGainSettingService.deleteByPrimaryKey(memberGainId);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/addMemberGainSetting")
    public TResponse addMemberGainSetting(RcMemberGainSetting memberGainSetting, List<RcMemberGainGradeSetting> list) {
        memberGainSettingService.addMemberGainSetting(memberGainSetting, list);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/updateMemberGainSetting")
    public TResponse updateMemberGainSetting(RcMemberGainSetting memberGainSetting,
                                          List<RcMemberGainGradeSetting> addGradeList,
                                          List<RcMemberGainGradeSetting> editGradeList,
                                          List<RcMemberGainGradeSetting> delGradeList) {
        memberGainSettingService.updateMemberGainSetting(memberGainSetting, addGradeList, editGradeList, delGradeList);
        return TResponse.SUCCESS();
    }
    @ResponseBody
    @RequestMapping("/saveMemberGain")
    public TResponse saveMemberGain(RcMemberGainSetting memberGainSetting, @RequestParam(value = "file1", required = false) MultipartFile file1) {
        TenantUser user = ShiroUtils.getSessionUser();
        memberGainSetting.setLastUpdatedBy(user.getLoginName());
        memberGainSetting.setLastUpdatedTime(new Date());
        try {

            if (file1.getSize() != 0) {
                if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
                    String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
                    memberGainSetting.setGainLogo(imgUrl);
                }
                /*TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file1);
                if (tResponse.getStatus() == 200) {
                    memberGainSetting.setGainLogo((String) tResponse.getData());
                } else {
                    return tResponse;
                }*/
            }
            if(memberGainSetting.getMemberGainId()!=null){
                //如果编辑没有上传图片、则取旧的图片
                if(StringUtils.isBlank(memberGainSetting.getGainLogo())){
                    RcMemberGainSetting oldSetting =  memberGainSettingService.selectByPrimaryKey(memberGainSetting.getMemberGainId());
                    memberGainSetting.setGainLogo(oldSetting.getGainLogo());
                }
               /* int code = memberGainSettingService.editGain(memberGainSetting);
                if (code==0){
                    logger.error("编辑会员权益失败");
                    return TResponse.FAIL("编辑会员权益失败");
                }*/
                memberGainSettingService.updateByPrimaryKey(memberGainSetting);
            }else{
                memberGainSetting.setCreatedBy(user.getLoginName());
                memberGainSetting.setCreatedTime(new Date());
                /*int code = memberGainSettingService.saveGain(memberGainSetting);
                if (code==0){
                    logger.error("新增会员权益失败");
                    return TResponse.FAIL("新增会员权益失败");
                }*/
                memberGainSettingService.insertSelective(memberGainSetting);
            }
        } catch (Exception e) {
            logger.error("操作失败", e);
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public TResponse updateStatus(Long id, String status) {
        RcMemberGainSetting info = memberGainSettingService.selectByPrimaryKey(id);
        info.setStatus(status);
        memberGainSettingService.updateByPrimaryKeySelective(info);
        return TResponse.SUCCESS();
    }

}
